#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <filesystem>

using namespace std;
typedef long long ll;

vector<int> g[11];
int v[11];
ll ans, sum;

void dfs(int d, int pre, int val, int x, int f) {
    if(d == 6) {
        ans = min(ans, sum - val + x);
        return;
    }
    for(int i = 0; i <= 9; i++) {
        if(!g[i].size()) continue;
        if(i == 0) {
            if(f) {
                dfs(d + 1, -1, val + v[i], 10 * x + i, f ? i == 0 : 0);
                continue;
            }
        }
        int now = upper_bound(g[i].begin(), g[i].end(), pre) - g[i].begin();
        if(now >= g[i].size()) continue;
        dfs(d + 1, g[i][now], val + v[i], 10 * x + i, f ? i == 0 : 0);
    }
}

void solve() {
    string s;
    int c, t;
    cin >> c >> t;
    while(t--) {
        for(int i = 1; i <= 9; i++) g[i].clear();
        g[0].push_back(0);
        cin >> s;
        for(int i = 1; i <= 9; i++) cin >> v[i];
        sum = 0;
        for(int i = 0; i < s.size(); i++) {
            sum += v[s[i] - '0'];
            g[s[i] - '0'].push_back(i);
        }
        ans = sum;
        dfs(1, -1, 0, 0, 1);
        cout << ans << endl;
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    
    // 创建sample目录
    filesystem::create_directory("sample");
    
    // 处理data目录下的所有测试数据
    for(int i = 1; i <= 25; i++) {
        string in_file = "data/bargain" + to_string(i) + ".in";
        string out_file = "data/bargain" + to_string(i) + ".out";
        
        freopen(in_file.c_str(), "r", stdin);
        freopen(out_file.c_str(), "w", stdout);
        
        solve();
        
        // 如果是前5组数据，复制到sample目录
        if(i <= 5) {
            string sample_in = "sample/bargain" + to_string(i) + ".in";
            string sample_out = "sample/bargain" + to_string(i) + ".ans";
            filesystem::copy_file(in_file, sample_in, filesystem::copy_options::overwrite_existing);
            filesystem::copy_file(out_file, sample_out, filesystem::copy_options::overwrite_existing);
        }
    }
    
    return 0;
} 